package work.servlet.sing;

import tool.classes.log.UserLog;
import tool.property.log.UserProperty;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Base64;

@WebServlet(name = "ServletLogIn", value = "/log")
public class ServletLogIn extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        password = Base64.getEncoder().encodeToString(password.getBytes());

        UserLog ui = new UserLog(new UserProperty(email, password));
        int b = ui.login();

        // 登录失败，重新登录, 进入登录界面
        if (b < 0) {
            response.sendRedirect("/");
        } else {
            request.getSession().setAttribute("level", b);
            Cookie cookie = new Cookie("email", email);
            // 保持登录 Cookie/Session待定
            if (remember != null) {
                // 添加 cookie 保证持续登录
                cookie.setMaxAge(60 * 60 * 24 * 7);
            }
            response.addCookie(cookie);
            response.sendRedirect("/home");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("/");
    }
}
